package mongoc

import (
	"context"
	"go_server/conf"
	"log"
	"strings"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
)

var mongodb *mongo.Client

func initMongo() {
	url := strings.Join([]string{"mongodb://", conf.ConfigInfo.Mongo.Address}, "")
	log.Printf("%v\n", url)
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	c, err := mongo.Connect(ctx, options.Client().ApplyURI(url))
	if err != nil {
		log.Fatal("mongo连错误\n", err)
	}
	// 测试连通性
	if err := c.Ping(context.TODO(), readpref.Primary()); err != nil {
		log.Fatal("连接mongo服务失败\n", err)
	}
	log.Println("mongo服务连接成功")
	mongodb = c
}
func MongoClient() *mongo.Client {
	if mongodb == nil {
		initMongo()
	}
	return mongodb
}
func GetColl(TableName string) *mongo.Collection {
	return mongodb.Database(conf.ConfigInfo.Mongo.Database).Collection(TableName)
}
